<template>
  <div class="confirmOrder">
    <!-- 标题 -->
    <van-nav-bar
      title="确认订单"
      left-arrow
      @click-left="$router.back()"
      @click-right="$router.push('/profile')"
      class="navBar"
    >
      <van-icon slot="right" name="user-o" />
    </van-nav-bar>
    <!-- 地址 -->
    <van-cell
      is-link
      icon="location-o"
      class="address"
      @click="
        $router.push(
          `/confirmOrder/chooseAddress/?id=${userInfo.user_id}&sig=${address.id}`
        )
      "
    >
      <template slot="title">
        <span class="name">{{ address.name }}</span>
        <span class="sex">{{ address.sex | userSex }}</span>
        <span>{{ address.phone }}</span>
      </template>
      <template slot="label">
        <span class="position">{{ address.tag }}</span>
        <span>{{ address.address }}</span>
      </template>
    </van-cell>
    <!-- 送达时间 -->
    <van-cell title="送达时间" class="time">
      <template>
        <div class="plan">尽快送达 | 预计 {{ sendTime }}</div>
        <div class="send">蜂鸟专送</div>
      </template>
    </van-cell>
    <!-- 支付方式 -->
    <van-cell-group class="pay">
      <van-cell
        title="支付方式"
        :value="payMethod.name"
        is-link
        @click="show = true"
      />
      <van-cell title="红包" value="暂时只在饿了么APP中支持" />
    </van-cell-group>
    <!-- 商品 -->
    <van-cell-group class="items">
      <van-cell class="username">
        <template slot="title">
          <van-image
            fit="cover"
            :src="'https://elm.cangdu.org/img/' + userInfo.avatar"
          />
          <span>{{ address.name }}</span>
        </template>
      </van-cell>
      <van-cell :title="item.name" v-for="item in goods" :key="item.id">
        <template>
          <span class="red">x {{ item.quantity }}</span>
          &nbsp;&nbsp;
          <span>￥{{ item.price }}</span>
        </template>
      </van-cell>
      <van-cell
        :title="item.name"
        :value="'￥' + item.price"
        v-for="item in extra"
        :key="item.id"
      />
      <van-cell title="配送费" :value="'￥' + deliver_amount" />
      <van-cell :title="'订单 ￥' + total">
        <template>
          <p class="red">待支付</p>
          <p class="red">￥{{ total }}</p>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 备注 -->
    <van-cell-group>
      <van-cell
        title="订单备注"
        value="口味、偏好等"
        is-link
        @click="$router.push(`/confirmOrder/remark?id=${cart_id}`)"
      />
      <van-cell
        title="发票抬头"
        value="不需要开发票"
        is-link
        @click="$router.push('/confirmOrder/invoice')"
      />
    </van-cell-group>
    <!-- 结算 -->
    <div class="footer">
      <span class="money">待支付 : {{ total }}</span>
      <van-button type="primary" @click="submit">确认下单</van-button>
    </div>
    <!-- 选择支付方式 -->
    <van-popup
      v-model="show"
      round
      position="bottom"
      :style="{ height: '50%' }"
    >
      <van-nav-bar title="支付方式" />
      <van-cell-group>
        <van-cell
          clickable
          :title="item.name + item.description"
          v-for="item in payments"
          :key="item.id"
        >
          <template #right-icon>
            <van-checkbox
              :value="payMethod.id == item.id"
              :disabled="item.select_state === -1"
              @click="choosePay(item)"
            />
          </template>
        </van-cell>
      </van-cell-group>
    </van-popup>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getAddresses } from '@/api/profile'
import { addCarts, submit } from '@/api/order'

export default {
  name: 'confirmOrder',
  data() {
    return {
      address: {}, //当前地址
      show: false, //支付方式弹出层
      goods: [], //商品列表
      sendTime: '', // 送达时间
      payMethod: {}, //当前支付方式
      payments: [], //所有支付方式
      extra: {}, // 额外收费
      deliver_amount: 0, // 配送费
      total: 0, //总金额
      invoice: {}, //发票
      cart_id: '', //购物车ID
      restaurant_id: '', //餐馆ID
      remark: [],
      entities: JSON.parse(sessionStorage.getItem('KEY_LIST')),
      id: this.$route.query.id
    }
  },
  methods: {
    // 获取用户地址
    async getAddresses() {
      const { data } = await getAddresses(this.userInfo.user_id)
      this.address = data[0]
    },
    // 商品加入购物车
    async addCarts() {
      this.entities = this.entities.map(item => {
        return {
          name: item.title,
          price: 20,
          quantity: item.__v,
          specs: ['']
        }
      })
      const { data } = await addCarts({
        restaurant_id: this.id,
        geohash: '31.22299,121.36025',
        entities: [this.entities]
        //  [
        //   [
        //     {
        //       // attrs: [],
        //       // extra: {},
        //       // id: 23725,
        //       name: 'ew1',
        //       // packing_fee: 0,
        //       price: 20,
        //       quantity: 4,
        //       // sku_id: 23698,
        //       specs: ['']
        //       // stock: 1000
        //     }
        //   ]
        // ]
      })
      // console.log(data);
      this.goods = data.cart.groups[0]
      this.sendTime = data.delivery_reach_time
      this.payments = data.payments
      this.extra = data.cart.extra
      this.deliver_amount = data.cart.deliver_amount
      this.total = data.cart.total
      this.cart_id = data.cart.id
      this.restaurant_id = data.cart.restaurant_id
      this.invoice = data.invoice
    },
    // 选择支付方式
    choosePay(item) {
      if (item.select_state === -1) {
        return this.$toast.fail('暂不支持该支付方式!')
      }
      this.payMethod = item
      this.show = false
    },
    // 确认下单
    async submit() {
      console.log(this.entities)
      const { data } = await submit({
        user_id: this.userInfo.user_id,
        cart_id: this.cart_id,
        address_id: this.address.address_detail,
        restaurant_id: this.restaurant_id,
        remark: this.remark,
        entities: [this.entities]
      })
      if (data.status !== 1) {
        return this.$toast.fail('下单失败，请重试!')
      }
      await this.$toast.success('下单成功!')
      this.$router.push('/confirmOrder/payment')
    }
  },
  // 判断跳转来源
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (from.path !== '/confirmOrder/chooseAddress/') {
        vm.getAddresses()
      }
    })
  },
  computed: {
    ...mapState(['userInfo'])
  },
  created() {
    // const address = sessionStorage.getItem('address')
    // if(address){
    //   this.address = JSON.parse(address)
    // }
    // 事件主线传参（选择地址）
    this.$bus.$on('chooseAddress', address => {
      this.address = address
    })
    //（添加备注）
    this.$bus.$on('addRemark', remark => {
      this.remark = remark
    })
    //  this.remark =  sessionStorage.getItem('addRemark')
    // 获取订单详情
    this.addCarts()
  },
  filters: {
    // 转换性别参数
    userSex(val) {
      if (val === 1) {
        return '男'
      } else if (val === 2) {
        return '女'
      } else {
        return
      }
    }
  }
}
</script>

<style lang="less" scoped>
.confirmOrder {
  padding: 46px 0 44px;
  .red {
    color: red;
  }
  /deep/.navBar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    background-color: #4e7ee8;
    .van-nav-bar__title,
    .van-icon-user-o,
    .van-icon-arrow-left {
      font-size: 20px;
      color: #fff;
    }
  }
  .address {
    margin-bottom: 10px;
    align-items: center;
    .van-icon-location-o {
      margin-right: 10px;
      font-size: 18px;
      color: #4e7ee8;
    }
    .van-cell__right-icon {
      font-size: 20px;
    }
    .van-cell__label {
      font-size: 14px;
    }
    .name {
      margin-right: 5px;
      font-size: 18px;
      font-weight: 700;
    }
    .sex {
      margin-right: 5px;
    }
    .position {
      display: inline-block;
      padding: 0 5px;
      margin-right: 5px;
      border-radius: 3px;
      background-color: #4cd964;
      color: #fff;
    }
  }
  .time {
    .van-cell__title {
      display: flex;
      align-items: center;
      font-size: 20px;
      font-weight: 700;
    }
    .send {
      display: inline-block;
      padding: 0 5px;
      border-radius: 3px;
      background-color: #3190e8;
      color: #fff;
    }
    .plan {
      font-size: 16px;
      color: #3190e8;
      margin-bottom: 5px;
    }
  }
  .pay {
    margin-top: 10px;
  }
  .items {
    margin: 10px 0;
    .van-cell__title,
    .van-cell__value {
      font-size: 16px;
      /deep/.van-image__img {
        width: 30px;
        height: 30px;
        margin-right: 10px;
      }
    }
    .username {
      .van-cell__title {
        display: flex;
        align-items: center;
        font-size: 20px;
      }
    }
  }
  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    .money {
      display: inline-block;
      padding-left: 15px;
      flex: 1;
      height: 44px;
      line-height: 44px;
      background-color: #3c3c3c;
      font-size: 20px;
      color: #fff;
    }
    .van-button__content {
      .van-button__text {
        font-size: 18px;
      }
    }
  }
}
</style>
